package com.recSys.util;

import com.recSys.model.UserOrgBehavior;
import net.librec.recommender.item.GenericRecommendedItem;
import net.librec.recommender.item.RecommendedItem;
import net.librec.util.FileUtil;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;
import pers.sharedFileSystem.configManager.Config;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import static com.recSys.util.LogRecord.INFO;

/**
 * 文件操作类
 *
 */
public class FileHandler {

	public static final String TREAL_STORE_PREFIX = Config.getNodeByNodeId("technologyFilePath").getServerNode().URL;
	public static final String TTEMP_STORE_PREFIX = Config.getNodeByNodeId("TempFileStoreNode").getServerNode().URL;

	public static void main(String[] args) {
	}

	/**
	 * 将xml转成json
	 * 
	 * @param xml
	 * @return json 串
	 */
	public static String xmlToJSON(String xml) {
		XMLSerializer xmlSerializer = new XMLSerializer();
		JSON json = xmlSerializer.read(xml);
		System.out.println("xml--->json \n" + json.toString());
		return json.toString();
	}

	/**
	 * 将 json串转xml
	 * 
	 * @param jsonStr
	 * @return xml
	 */
	public static String jsonToXML(String jsonStr) {
		JSONObject json = JSONObject.fromObject(jsonStr);
		XMLSerializer xmlSerializer = new XMLSerializer();
		xmlSerializer.setRootName("user_info");
		xmlSerializer.setTypeHintsEnabled(false);
		String xml = xmlSerializer.write(json);
		System.out.println("json--->xml \n" + xml);
		return xml;
	}

	/**
	 * read the config file to get the config value.
	 * @param fileName the properties file path
	 * @param name   the item of properties file content.
	 * @return the item's value
	 */
	public  String readConfig(String fileName, String name) {
		try {
			InputStream in = this.getClass().getResourceAsStream(fileName);
			Properties p = new Properties();
			p.load(in);
			String ret = p.getProperty(name, "");
			in.close();
			return ret;
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}


	public void saveUserOrgRating(List<UserOrgBehavior> uobList){
		if (uobList != null && uobList.size() > 0) {
			String fileName = "/com/recSys/config/offlineTaskOutput.properties";
			// make output path
			String outputPath = readConfig(fileName,"userOrgRatingPath");
			INFO.info("Result path is " + outputPath);
			// convert itemList to string
			StringBuilder sb = new StringBuilder();
			for (UserOrgBehavior uob : uobList) {
				int userId = uob.getUserID();
				int itemId = uob.getOrgID();
				String value = String.valueOf(uob.getOverallRating(uob));
				sb.append(userId).append(",").append(itemId).append(",").append(value).append("\n");
			}
			String resultData = sb.toString();
			// save resultData
			try {
				FileUtil.writeString(outputPath, resultData);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void saveRecommendOrgListByItemKNN(List<RecommendedItem> recommendedItemList){
		if (recommendedItemList != null && recommendedItemList.size() > 0) {
			String fileName = "/com/recSys/config/offlineTaskOutput.properties";
			// make output path
			String outputPath = readConfig(fileName,"recommendOrgListByItemKNNPath");
			INFO.info("Result path is " + outputPath);
			// convert itemList to string
			StringBuilder sb = new StringBuilder();
			for (RecommendedItem item : recommendedItemList) {
				String userId = item.getUserId();
				String itemId = item.getItemId();
				String value = String.valueOf(item.getValue());
				sb.append(userId).append(",").append(itemId).append(",").append(value).append("\n");
			}
			String resultData = sb.toString();
			// save resultData
			try {
				FileUtil.writeString(outputPath, resultData);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public List<RecommendedItem> readRecommendList(String fileName, int userId) throws IOException {
        List<RecommendedItem> recommendedItemList = new ArrayList<>();
	    File file = new File(fileName);
	    if(file.isFile() && file.exists()) {
            FileInputStream fis = new FileInputStream(file);
            InputStreamReader reader = new InputStreamReader(fis);
            BufferedReader bufferedReader = new BufferedReader(reader);
            String lineTxt = null;
            while ((lineTxt = bufferedReader.readLine()) != null)
            {
                String[] line = lineTxt.split(",");
                if(String.valueOf(userId).equals(line[0])){
                    GenericRecommendedItem item = new GenericRecommendedItem(line[0],line[1],Double.valueOf(line[2]));
                    recommendedItemList.add(item);
                }
            }
            bufferedReader.close();
            reader.close();
        } else {
            System.out.println("找不到指定的文件");
        }
        return recommendedItemList;
	}
}
